package cn.wolfcode.luowowo.search.service.impl;

import cn.wolfcode.luowowo.search.domain.StrategyTemplate;
import cn.wolfcode.luowowo.search.domain.TicketTemplate;
import cn.wolfcode.luowowo.search.query.StatisVoQuery;
import cn.wolfcode.luowowo.search.query.TicketSeachQuery;
import cn.wolfcode.luowowo.search.repository.TicketSearchRepository;
import cn.wolfcode.luowowo.search.service.ITicketSearchService;
import cn.wolfcode.luowowo.search.vo.StatisVo;
import com.alibaba.dubbo.config.annotation.Service;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.composite.*;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;

import java.util.*;

@Service
public class TicketSearchServiceImpl implements ITicketSearchService {
    @Autowired
    private TicketSearchRepository repository;


    @Override
    public void saveOrUpdate(TicketTemplate ticketTemplate) {
        repository.save( ticketTemplate );
    }

    @Override
    public  List <TicketTemplate> query(TicketSeachQuery qo) {


        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.withQuery( QueryBuilders.termQuery( "destId", qo.getDestId() ) );
        builder.withPageable( PageRequest.of( qo.getCurrentPage() - 1, qo.getPageSize() ) );
        List <TicketTemplate> content = repository.search( builder.build() ).getContent();
        return content;

    }

    @Override
    public List <String> selectTicketService() {
        List <String> list = new ArrayList <>();
        Iterable <TicketTemplate> service = repository.search( QueryBuilders.existsQuery( "service" ) );
        for (TicketTemplate template : service) {
            list.add( template.getService() );
        }


        return list;


    }

    @Override
    public  List <TicketTemplate> selectCommendTickets() {
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.withPageable( PageRequest.of( 0, 10, Sort.Direction.DESC, "saleNum" ) );
        Page <TicketTemplate> search = repository.search( builder.build() );
        List <TicketTemplate> content = search.getContent();
        //去重

        return content;
    }


}
